//
//  lvfjHttpRequest.m
//  lvfj
//
//  Created by 吕飞俊 on 15/9/29.
//  Copyright © 2015年 Goudu KuaiEx Technology(Shenzhen)Co.,ltd. All rights reserved.
//

#import "lvfjHttpRequest.h"
#import "StringUtils.h"
#import "lvfjCommon.h"
#import "AFHTTPRequestOperationManager.h"

@implementation lvfjHttpRequest

+(AFHTTPRequestOperationManager *)setRequestOperationManager{
    //管理
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //接受
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //请求
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    //设置类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    //是否要信任无效或过期的SSL证书
    manager.securityPolicy.allowInvalidCertificates = YES;
    //超时时间
    manager.requestSerializer.timeoutInterval = TimeoutInterval;
    return manager;
}

+(void)POST:(NSString *)url
 parameters:(NSDictionary *)parameters
    success:(void (^)(NSDictionary *))success
    failure:(void (^)(NSError *))failure{
    AFHTTPRequestOperationManager *manager = [self setRequestOperationManager];
#if lvfjLogin
    lvfjLog(@"开始请求:url=%@..........params:%@",url,parameters);
#endif
    //    __weak typeof(self) wSelf = self;
    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
        //        __strong typeof(wSelf) sSelf = wSelf;
        //         NSDictionary *dic = (NSDictionary *)responseObject;
        
        //         if (![dic isKindOfClass:[NSDictionary class]]){
        //             dic = @{@"errcode":@"-1",@"msg":@""};
        //             lvfjLog(@"非 NSDictionary 类型");
        //         }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
#if lvfjLogin
        lvfjLog(@"请求成功：dic=%@",dic);
#endif
        success(dic);
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        //        __strong typeof(wSelf) sSelf = wSelf
#if lvfjLogin
        
        lvfjLog(@"请求失败:url=%@",url);
        lvfjLog(@"error: %@", error);
        lvfjLog(@"error.localizedDescription------%@",error.localizedDescription);
        lvfjLog(@"error.code)------:%zd",error.code);
#endif
        NSString *str = [NSString stringWithFormat:@"请求失败:%@",![StringUtils isEmptyString:error.localizedDescription]?error.localizedDescription:url];
        if (error.code == -1009){
            str = @"似乎已断开了与互联网的连接。";
            //            [UIAlertView showAlertMsg:@"似乎已断开了与互联网的连接。"];
        }else if (error.code == 3840){
            str = @"非 Json 格式";
            //            [UIAlertView showAlertMsg:@"非 Json 格式"];
        }else{
            //            [UIAlertView showAlertMsg:str];
        }
        //        lvfjLog(@"%@",str);
        
        failure(error);
    }];
}

//+ (void)postUploadWithUrl:(NSString *)url
//               parameters:(NSDictionary *)parameters imgs:(NSArray *)imgs success:(void (^)(NSDictionary *))success failure:(void (^)(NSError *))failure{
//    AFHTTPRequestOperationManager *manager = [lvfjHttpRequest setRequestOperationManager];
//
//    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
//
//        [imgs enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [formData appendPartWithFileData:UIImagePNGRepresentation(obj) name:@"mobile_upload_file" fileName:fileName mimeType:@"image/png"];
//        }];
//
//
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//        lvfjLog(@"请求成功:url=%@..........data=%@",url,dic);
//        if (success) {
//            success(dic);
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        if (failure) {
//            lvfjLog(@"请求失败:url=%@",url);
//            lvfjLog(@"error: %@", error);
//            lvfjLog(@"error.localizedDescription------%@",error.localizedDescription);
//            lvfjLog(@"error.code)------:%zd",error.code);
//            failure(error);
//        }
//    }];
//}

+ (void)postConstructingBodyWithUrl:(NSString *)url
                         parameters:(NSDictionary *)parameters
                            formDic:(NSDictionary *)formDic
                             imgDic:(NSDictionary *)imgDic
                            success:(void (^)(NSDictionary *))success
                            failure:(void (^)(NSError *))failure{
    
    AFHTTPRequestOperationManager *manager = [lvfjHttpRequest setRequestOperationManager];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        if (imgDic.count) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            
            [imgDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                [formData appendPartWithFileData:UIImagePNGRepresentation(obj) name:key fileName:fileName mimeType:@"image/png"];
#if lvfjLogin
                lvfjLog(@"key:%@,fileName:%@",key,fileName);
#endif
            }];
        }
        
        if (formDic.count) {
            [formData appendPartWithFormData:[NSJSONSerialization dataWithJSONObject:formDic options:NSJSONWritingPrettyPrinted error:nil] name:@"params"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        lvfjLog(@"请求成功:url=%@..........data=%@",url,dic);
        if (success) {
            success(dic);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            lvfjLog(@"请求失败:url=%@",url);
            lvfjLog(@"error: %@", error);
            lvfjLog(@"error.localizedDescription------%@",error.localizedDescription);
            lvfjLog(@"error.code)------:%zd",error.code);
            failure(error);
        }
    }];
}

+(void)GET:(NSString *)url
parameters:(id)parameters
   success:(void (^)(NSDictionary *))success
   failure:(void (^)(NSError *))failure{
    AFHTTPRequestOperationManager *manager = [lvfjHttpRequest setRequestOperationManager];
    [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //        __strong typeof(wSelf) sSelf = wSelf;
        //         NSDictionary *dic = (NSDictionary *)responseObject;
        
        //         if (![dic isKindOfClass:[NSDictionary class]]){
        //             dic = @{@"errcode":@"-1",@"msg":@""};
        //             lvfjLog(@"非 NSDictionary 类型");
        //         }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
#if lvfjLogin
        lvfjLog(@"请求成功：dic=%@",dic);
#endif
        success(dic);
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        //        __strong typeof(wSelf) sSelf = wSelf
#if lvfjLogin
        
        lvfjLog(@"请求失败:url=%@",url);
        lvfjLog(@"error: %@", error);
        lvfjLog(@"error.localizedDescription------%@",error.localizedDescription);
        lvfjLog(@"error.code)------:%zd",error.code);
#endif
        NSString *str = [NSString stringWithFormat:@"请求失败:%@",![StringUtils isEmptyString:error.localizedDescription]?error.localizedDescription:url];
        if (error.code == -1009){
            str = @"似乎已断开了与互联网的连接。";
            //            [UIAlertView showAlertMsg:@"似乎已断开了与互联网的连接。"];
        }else if (error.code == 3840){
            str = @"非 Json 格式";
            //            [UIAlertView showAlertMsg:@"非 Json 格式"];
        }else{
            //            [UIAlertView showAlertMsg:str];
        }
        //        lvfjLog(@"%@",str);
        
        failure(error);
        
    }];
    
}

//- (void)cancelAllOperations{
//    [self.manager.operationQueue cancelAllOperations];
//}

+(NSArray *)dowloadImgs:(NSArray *)urlArray{
    __block NSMutableArray *array = [[NSMutableArray alloc]init];
    [urlArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSURL *url = [NSURL URLWithString:obj];
        NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingMapped error:nil];
        UIImage *img = [UIImage imageWithData:data];
        [array addObject:img];
    }];
    
    return [NSArray arrayWithArray:array];
}

@end
